import { defineStore } from "pinia";
import Cookies from "js-cookie";
import axios from "axios";
import routes from '@/router/router'
const modules = import.meta.glob("../views/**/*.vue");

export const useMarkStore = defineStore("mark", {
  state: () => ({
    pageRoutes: <any>[], //当前页面缓存路由
    asyncRoutes: <any>[],//从接口获取到的路由数组
  }),
  getters: {
  },
  actions: {
    SET_ROUTES(_routes: any[]){
        this.$state.asyncRoutes=_routes
        this.$state.pageRoutes=routes.concat(_routes)

    },
    getRouter() {
      let _id = Cookies.get("id");
      if (_id) {
        return new Promise((resolve, reject) => {
          axios.post("/api/getRoutes", { id: _id }).then((res) => {
            console.log(res);
            let _data = res.data;
            let newData = this.parseRouter(_data);
            this.SET_ROUTES(newData)
            resolve(newData);
          });
        });
      }
    },
    parseRouter(_data: Array<any>) {
      //处理后端返回的路由数据=》vite项目能解析的路由格式
      let _newArr: Array<any> = [];
      _data.forEach((item: any) => {
        let newItem = Object.assign({}, item);
        let comp = item.component;

        newItem.component = modules[`../views${comp}`];
        _newArr.push(newItem);
      });
      return _newArr;
    },
  },
  getButtonCode(){
    //按钮权限思路：
    //1.在登录的时候拉取按钮权限编码code['EXPORT_LIST','OPEN_MODAL']
    //2.将编码缓存本地
    //3.页面通过v-if控制按钮或是自义定指令控制按钮

  }
});
